package com.coalmine.api.controller;

import com.alibaba.fastjson.JSON;
import com.coalmine.api.domain.ApiGroup;
import com.coalmine.api.service.IApiGroupService;
import com.coalmine.common.annotation.Log;
import com.coalmine.common.constant.HttpStatus;
import com.coalmine.common.core.controller.BaseController;
import com.coalmine.common.core.domain.AjaxResult;
import com.coalmine.common.core.page.TableDataInfo;
import com.coalmine.common.enums.BusinessType;
import com.coalmine.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * api组信息表 前端控制器
 * </p>
 *
 * @author 尚郑
 * @since 2022-04-01
 */
@Api(value = "API分组", tags = {"API分组接口"})
@RestController
@RequestMapping("/api/group")
public class ApiGroupController extends BaseController {
    @Autowired
    IApiGroupService iApiGroupService;

    /**
     * API创建
     */
    @ApiOperation("新增API分组")
    @Log(title = "API分组", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('api:group:add')")
    @PostMapping("/add")
    public AjaxResult addApiGroup(@RequestBody ApiGroup apiGroup) {
        String username = getUsername();
        apiGroup.setCreateBy(username);
        apiGroup.setUpdateBy(username);
        return iApiGroupService.addApiGroup(apiGroup);
    }

    @ApiOperation("更新api分组")
    @Log(title = "API分组", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('api:group:edit')")
    @PutMapping("/update")
    public AjaxResult updateApiGroup(@RequestBody ApiGroup apiGroup) {
        apiGroup.setUpdateBy(getUsername());
        return iApiGroupService.updateApiGroup(apiGroup);
    }

    @ApiOperation("删除api分组")
    @Log(title = "API分组", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('api:group:remove')")
    @DeleteMapping("/deleteApiGroup/{id}")
    public AjaxResult deleteApiGroup(@PathVariable String id) {
        return iApiGroupService.deleteApiGroupById(id);
    }

    @ApiOperation("api分组下拉框")
    @GetMapping("/getAllGroup")
    public AjaxResult getAllGroup() {
        List<ApiGroup> all = iApiGroupService.getAll();
        return AjaxResult.success(all);
    }

    @ApiOperation("api分组列表展示")
    @PreAuthorize("@ss.hasPermi('api:group:list')")
    @GetMapping("/getAllGroupList")
    public TableDataInfo getAllGroupList() {
        startPage();
        List<ApiGroup> list = iApiGroupService.getAllGroupList();
        //List<ApiGroup> collect = list.stream().sorted(Comparator.comparing(ApiGroup::getUpdateTime).reversed()).collect(Collectors.toList());
        return getDataTable(list);
    }

    @ApiOperation("api分组导出")
    @Log(title = "API分组", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('api:group:export')")
    @GetMapping("/downloadGroupConfig")
    public void downloadGroupConfig(String ids, HttpServletResponse response) {
        List<String> collect = Arrays.asList(ids.split(","));
        final List<ApiGroup> list = iApiGroupService.selectBatch(collect);
        String s = JSON.toJSONString(list);
        response.setContentType("application/x-msdownload;charset=utf-8");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(s.getBytes("utf-8"));
        } catch (Exception e) {
            throw new ServiceException("导出失败",HttpStatus.ERROR);
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("api分组导入")
    @Log(title = "API分组", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('api:group:import')")
    @PostMapping(value = "/importGroup", produces = "application/json;charset=UTF-8")
    public AjaxResult importGroup(@RequestParam("file") MultipartFile file) throws IOException {
        String s = IOUtils.toString(file.getInputStream(), "utf-8");
        List<ApiGroup> configs = JSON.parseArray(s, ApiGroup.class);
        try {
            iApiGroupService.insertBatch(configs);
        }catch (Exception e){
           //logger.error("分组导入失败",e.getMessage());
            throw new ServiceException("导入失败", HttpStatus.ERROR);
        }
        return AjaxResult.success();

    }
    @ApiOperation("根据api分组ID查询")
    @PreAuthorize("@ss.hasPermi('api:group:query')")
    @GetMapping("/findGroupById/{id}")
    public AjaxResult findGroupById(@PathVariable String id) {
        ApiGroup groupById = iApiGroupService.findGroupById(id);
        return AjaxResult.success(groupById);
    }


}
